package file.server

import groovy.json.JsonOutput
import org.springframework.security.access.annotation.Secured

import java.text.SimpleDateFormat

import static org.springframework.http.HttpStatus.*

@Secured(['permitAll'])
class AttachmentController
{
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    AttachmentService attachmentService

    @Secured('permitAll')
    def upload()
    {
        log.info "******************** upload inParams ************************"

        // def appSessionId = request.getParameter("appSessionId")
        def file = request.getFile("file")
        def fileType = request.getParameter("fileType")

        // log.info "appSessionId: " + appSessionId + "; file: " + file + "; fileType: " + fileType

        // if (appSessionId == null || appSessionId == '')
        // {
        //     log.error "请登录\n"
        //     def errors = [errorCode: 4300, errorMessage: "请登录"]
        //     render JsonOutput.toJson(errors), status: 200
        //     return
        // }
        // User user = User.findByAppSessionId(appSessionId)
        // if (!user)
        // {
        //     log.error "您的账号已在别处登录！如非本人操作，请及时修改密码\n"
        //     def errors = [errorCode: 4400, errorMessage: "您的账号已在别处登录！如非本人操作，请及时修改密码"]
        //     render JsonOutput.toJson(errors), status: 200
        //     return
        // }
        if (!file)
        {
            log.error "上传文件不能为空\n"
            def errors = [errorCode: 5500, errorMessage: "上传文件不能为空"]
            render JsonOutput.toJson(errors), status: 200
            return
        }
        if (!fileType)
        {
            log.error "上传文件类型不能为空\n"
            def errors = [errorCode: 5501, errorMessage: "上传文件类型不能为空"]
            render JsonOutput.toJson(errors), status: 200
            return
        }

        def externalId = UUID.randomUUID().toString()
        def webroot = servletContext.getRealPath("/")

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy")
        SimpleDateFormat sdf2 = new SimpleDateFormat("MM")
        SimpleDateFormat sdf3 = new SimpleDateFormat("dd")
        Date date = new Date()

        File folder = attachmentService.createFolder(webroot, sdf1.format(date), sdf2.format(date), sdf3.format(date))
        File fileImage = new File(folder, "${externalId}.${fileType}")
        file.transferTo(fileImage)

        log.info "******************** upload outParams ***********************"
        log.info "externalId: " + externalId + "\n"

        def resultMap = [externalId: externalId]
        render JsonOutput.toJson(resultMap), status: 200
    }

    @Secured('permitAll')
    def query()
    {
        def externalId = params['externalId']
    }
}